package top.shmly.universal.utils.impl;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.shmly.universal.utils.HttpRequestUtil;
import top.shmly.universal.utils.ResponseJsonUtils;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ResponseJsonUtilsImpl implements ResponseJsonUtils {

    /**
     * 通过ServletResponse返回JSon数据
     *
     * @param servletResponse response
     * @param httpStatus      HTTP状态码
     * @param object          数据
     */
    @Override
    public  void sendMsgWithServletResponse(ServletResponse servletResponse, int httpStatus, Object object) {
        servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        servletResponse.setCharacterEncoding("UTF-8");
        //401状态
        ((HttpServletResponse) servletResponse).setStatus(httpStatus);
        PrintWriter printWriter = null;
        try {
            printWriter = servletResponse.getWriter();
            printWriter.append(JSONUtil.toJsonStr(object));
        } catch (IOException e) {
            log.error("返回信息异常:", e);
        } finally {
            assert printWriter != null;
            printWriter.close();
        }
    }

    /**
     * 通过ServletResponse返回JSon数据
     *
     * @param httpStatus HTTP状态码
     * @param object     数据
     */
    @Override
    public  void sendMsgWithServletResponse(int httpStatus, Object object) {
        HttpRequestUtil httpRequestUtil = HttpRequestUtilImpl.getInstance();
        ServletResponse servletResponse = httpRequestUtil.get(ServletRequestAttributes::getResponse);
        sendMsgWithServletResponse(servletResponse, httpStatus, object);
    }

    private ResponseJsonUtilsImpl() {
    }

    private static class SingletonHolder {
        private static final ResponseJsonUtilsImpl singletonInstance = new ResponseJsonUtilsImpl();
    }

    public static ResponseJsonUtilsImpl getInstance() {
        return ResponseJsonUtilsImpl.SingletonHolder.singletonInstance;
    }
}
